import React, { memo, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";
import { Form, Input, Button, message } from "antd";
import qs from "qs";

import { saveuseraction } from "./store/useractioncreater";
import { Loginwrap } from "./style";
import request from "../../service/request";

import Loginback from "@/components/loginback";
export default memo(function Login() {
  const dispatch = useDispatch();
  const history = useHistory();
  useEffect(() => {
    localStorage.removeItem("logining");
    localStorage.removeItem("persist:root");
  }, []);
  const onFinish = (values) => {
    request
      .post("travel/login", qs.stringify(values))
      .then((res) => {
        if (res) {
          message.success({
            content: "登录成功",
            style: {
              fontSize: 20,
            },
          });
          localStorage.setItem("logining", 1);
          dispatch(saveuseraction(res));
          if (values.userName === "admin") {
            history.push("/adminpage");
          } else {
            history.push("/home");
          }
        } else {
          message.error({
            content: "用户名不存在或密码错误",
            style: {
              fontSize: 20,
            },
          });
        }
      })
      .catch((err) => {
        console.log(err);
        console.log("登录接口出错");
      });
  };
  return (
    <Loginwrap>
      <Loginback></Loginback>
      <div className="logintitle">个人博客网</div>
      <div className="form1">
        <h1>Logining</h1>
        <Form
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          style={{ color: "red" }}
        >
          <Form.Item
            label="UserName"
            name="userName"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[
              {
                required: true,
                message: "Please input your password!",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className="toregister" onClick={(e) => history.push("/register")}>
        没有账号？立即注册
      </div>
    </Loginwrap>
  );
});
